<template>
	<div class="app-container" v-loading="data.mtloading">
		<el-form :model="data.info" :rules="data.rules" class="w-full" :label-width="language == 'en' ? '155' : '100px'"
			ref="ruleFormRef">

			<el-form-item :label="$t('goods.corner.activitName') + ':'" prop="fd_name" class="w-1/2">
				<el-input v-model="data.info.fd_name" :placeholder="$t('message.pleaseEnter')" />
			</el-form-item>

			<el-form-item :label="$t('goods.corner.timeType') + ':'" prop="timetype" class="w-1/2">
				<el-select v-model="data.timetype" :placeholder="$t('message.pleaseSelect')">
					<el-option :label="$t('goods.corner.timeLimit')" :value="1" />
					<el-option :label="$t('goods.corner.indefinite')" :value="2" />
				</el-select>
			</el-form-item>

			<el-form-item v-if="data.timetype == 1" :label="$t('date.activityTime') + ':'" prop="date" class="w-1/2">
				<el-date-picker v-model="data.info.date" :disabled-date="disabledDate" type="datetimerange"
					:range-separator="$t('public.to')" :start-placeholder="$t('date.startTimes')"
					:end-placeholder="$t('date.endTimes')" format="YYYY-MM-DD HH:mm:ss" time-format="A hh:mm:ss"
					value-format="x" :shortcuts="shortcuts" />
			</el-form-item>

			<el-form-item v-if="data.timetype == 2" :label="$t('date.activityTime') + ':'" prop="datel" class="w-1/2">
				<el-date-picker v-model="data.info.datel" :disabled-date="disabledDate" type="datetime"
					format="YYYY-MM-DD HH:mm:ss" value-format="x" style="width: 100%;"
					:placeholder="$t('message.pleaseSelect')" time-format="HH:mm" />
			</el-form-item>

			<el-form-item :label="$t('marketing.reduction.type') + ':'" prop="fd_type">
				<el-radio-group v-model="data.info.fd_type" @change="getradio(1)">
					<el-radio :value="1" :label="1" border>{{ $t('marketing.reduction.gift') }}</el-radio>
					<el-radio :value="2" :label="2" border>{{ $t('marketing.preferential.deduction') }}</el-radio>
					<el-radio :value="3" :label="3" border>{{ $t('marketing.preferential.surprise') }}</el-radio>
					<el-radio :value="4" :label="4" border>{{ $t('marketing.reduction.discount') }}</el-radio>
				</el-radio-group>
			</el-form-item>

			<el-form-item :label="$t('marketing.reduction.conditionType')" prop="condition_type">
				<el-radio-group v-model="data.info.condition_type" @change="getradio(2)">
					<el-radio :value="1" :label="1" border>{{ $t('marketing.preferential.minAmount') }}</el-radio>
					<el-radio :value="2" :label="2" border>{{ $t('marketing.reduction.minQuantity') }}</el-radio>
					<el-radio :value="3" :label="3" border>{{ $t('marketing.reduction.sku') }}</el-radio>
					<el-radio :value="0" :label="0" border :disabled="data.info.fd_type == 3 ? false : true">{{
						$t('marketing.reduction.Nolimit') }}</el-radio>
				</el-radio-group>
			</el-form-item>

			<el-form-item :label="$t('machine.marketing.Applicable') + ':'" prop="grouping" class="w-1/2"
				v-prmis="'machine_group_mg_getList'">

				<el-cascader :placeholder="$t('message.selectGroup')" style="width:40%;margin-right: 1%;" clearable
					:props="propss" v-model="data.groupValue" @change="getmping($event, 1)"
					@visible-change="onVisibleChange" />

				<el-select v-model="data.macping" :placeholder="$t('message.pleaseMachine')" clearable filterable
					style="width:40%;" @change="getmping($event, 2)">
					<el-option v-for="item in data.maclist" :key="item.m_id"
						:label="item.machine_id + '-' + item.machine_name" :value="item.machine_id" />
				</el-select>

				<div class="w-full dashed mt-2 p-2" v-if="data.grouping.length != 0">
					<el-tag v-for="item, key of data.grouping" :key="key" closable :disable-transitions="false"
						class="mr-2" :type="item.mg_id == undefined ? '' : 'warning'" size="large"
						@close="handleClose(key)">
						{{ item.machine_id || '' }}{{ item.mg_name || item.label || ' - ' + item.machine_name }}
					</el-tag>
				</div>

			</el-form-item>

			<el-form-item :label="$t('marketing.reduction.activityRules') + ':'" class="w-11/12">
				<div class="w-full border p-4">
					<draggable :list="data.info.content" item-key="id" group="people">
						<template #item="item">

							<div class=" relative flex mb-2 p-4 rounded" style="background: #FAFAFA;">

								<div class="w-4/12 mr-4" v-if="data.info.condition_type != 0">
									<el-input v-model="item.element.condition_value"
										:placeholder="$t('message.pleaseEnter')">
										<template #prepend>{{ getname(data.info.condition_type, 2) }}</template>
									</el-input>
								</div>

								<div class="w-3/12 mr-4" v-if="data.info.fd_type == 1 || data.info.fd_type == 3">
									<el-select v-model="item.element.g_id"
										:placeholder="$t('message.pleaseSelectProduct')" clearable filterable>
										<el-option v-for="item in data.godlist" :key="item.g_id"
											:label="item.g_id + ' - ' + item.g_name + ' ( ' + item.sku + ' )'"
											:value="item.g_id" />
									</el-select>
								</div>

								<div class="w-4/12 mr-4 flex flex-nowrap" v-if="data.info.fd_type != 1">
									<el-input v-model="item.element.active_value"
									:placeholder="data.info.fd_type == 4 ? $t('marketing.preferential.value') + '(' + $t('marketing.preferential.integer') + '),' + $t('marketing.reduction.example') : $t('message.pleaseEnter')">
										<template #prepend>{{ getname(data.info.fd_type, 1) }}</template>
									</el-input>
								</div>

								<div class="w-4/12 mr-4 flex flex-nowrap">
									<el-input v-model="item.element.fdc_sort" type="number"
										:placeholder="$t('message.sorted')">
										<template #prepend>{{ $t('marketing.preferential.SortValues') }}</template>
									</el-input>
								</div>

								<div class="w-1/12">
									<el-link v-if="item.index != 0" type="danger" :underline="false"
										@click="dels(item.index)">{{
											$t('public.del') }}</el-link>
								</div>
							</div>
						</template>
					</draggable>

					<div class="w-full">
						<el-tag class="cursor-pointer" type="warning" size="large" effect="dark" @click="addmance">
							{{ $t('marketing.reduction.addRule') }}
						</el-tag>
					</div>

				</div>
			</el-form-item>

			<el-form-item :label="$t('marketing.reduction.desc') + ':'" prop="desc" class="w-1/2">
				<el-input v-model="data.info.desc" type="textarea" :autosize="{ minRows: 8, maxRows: 10 }"
					:placeholder="$t('message.pleaseEnter')" />
			</el-form-item>
			<el-form-item :label="$t('marketing.preferential.mutually') + ':'" prop="exclusion" class="w-1/2">
				<el-switch v-model="data.info.exclusion" />
			</el-form-item>
			<div class="w-1/2 text-center mt-4 ml-6">
				<div class="inline-block">
					<el-button type="primary" @click="submit(ruleFormRef)">{{ $t('public.save') }}</el-button>
					<el-button @click="getinfo">{{ $t('public.cancel') }}</el-button>
				</div>
			</div>

		</el-form>
	</div>
</template>

<script lang="ts" setup>
import { useI18n } from 'vue-i18n'
const { t: $t } = useI18n()
import draggable from "vuedraggable";
import { getactivityfdFind, updateactivityfd } from "@/api/marketing";
import { getmachineList } from '@/api/machine';
import { getgroupList, getListgroupmg } from "@/api/machine_type";
import { getgoodsList } from '@/api/goods';
import { useRouter, useRoute } from "vue-router";
import { onMounted } from 'vue'
let language = ref()
const { locale } = useI18n()
onMounted(() => {
	language.value = locale.value
})
let ruleFormRef = ref<any>();
const router = useRouter()
const route = useRoute()

let shortcuts = [
	{
		text: '最近七天',
		value: () => {
			const start = new Date();
			const end = new Date();

			start.setTime(start.getTime() + 3600 * 1000 * 24 * 7);
			return [end, start];
		}
	},
	{
		text: '最近三十天',
		value: () => {
			const start = new Date();
			const end = new Date();

			start.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
			return [end, start];
		}
	},
	{
		text: '最近三个月',
		value: () => {
			const start = new Date();
			const end = new Date();
			start.setTime(start.getTime() + 3600 * 1000 * 24 * 90);
			return [end, start];
		}
	}
];

let data = reactive({
	groupValue: [],
	nodesData: [],
	mtloading: false, // 加载
	original: '', // 原始数据
	timetype: 1, // 1日期范围、2无限期
	maclist: [], // 设备列表
	godlist: [], // 商品列表

	macgrouping: [], // 设备分组
	bindmacping: [], // 设备分组绑定的设备
	grouping: [], // 展示分组/设备
	macping: '', // 选中的分组/设备

	info: {}, // 主体数据
	rules: { // 表单验证
		fd_name: { required: true, message: $t('message.pleaseEnter'), trigger: 'blur' },
		datel: { required: true, message: $t('message.pleaseSelect'), trigger: 'blur' },
		date: { required: true, message: $t('message.pleaseSelect'), trigger: 'change' },
		machineList: { required: true, message: $t('message.pleaseSelect'), trigger: 'change' },
		g_id: { required: true, message: $t('message.pleaseSelect'), trigger: 'change' },
	},
})
const propss = reactive(
	{
		checkStrictly: true,
		lazy: true,
		multiple: false,
		async lazyLoad(node: any, resolve: any) {
			const { level, value } = node
			let nodes = await getgroupList({ pid: value });
			if (nodes.state == 100 || nodes.state == 300) {
				resolve([]);
			}
			const nodesa = nodes.data.map((item) => ({
				value: item.mg_id,
				label: item.mg_id + '-' + item.mg_name
			}))
			nodes.data.forEach(item => {
				data.nodesData.push({
					value: item.mg_id,
					label: item.mg_id + '-' + item.mg_name
				})
			})
			resolve(nodesa);
		}
	}
)
// 整理主体信息
let getinfo = () => {
	let info = JSON.parse(data.original)
	data.info = {
		fd_id: info.fd_id,
		fd_name: info.fd_name,
		date: [],
		datel: '',
		fd_type: info.fd_type,
		condition_type: info.condition_type,
		desc: info.desc,
		machineList: [],
		content: info.content,
		delContent: [],
		exclusion: info.exclusion == 1 ? true : false
	}

	if (info.end_date == '' || info.end_date == null) {
		data.timetype = 2
		data.info.datel = Number(info.start_date + '000')
	} else {
		data.timetype = 1
		data.info.date = [Number(info.start_date + '000'), Number(info.end_date + '000')]
	}

	data.grouping = []

	for (let item of info.machineList) {
		data.grouping.push(item)
	}

}

// 获取活动数据
let getfind = async () => {
	let info = JSON.parse(decodeURI(route.query.l)).info
	data.mtloading = true
	await getactivityfdFind({ fd_id: info.fd_id }).then(res => {
		data.mtloading = false
		if (res.state == 200) {
			data.original = JSON.stringify(res.data)
			getinfo()
		}
	})

	// 获取设备信息
	await getmachineList().then(res => {
		if (res.state == 200) {
			data.maclist = res.data
		}
	})

	// 获取商品信息
	await getgoodsList().then(res => {
		if (res.state == 200) {
			data.godlist = res.data
		}
	})

	// 获取设备分组
	await getgroupList().then(res => {
		if (res.state == 200) {
			data.macgrouping = res.data
		}
	})

	// 获取分组中的设备
	await getListgroupmg().then(res => {
		if (res.state == 200) {
			data.bindmacping = res.data
		}
	})

}

// 日期选择
let disabledDate = (time: Date) => {
	return time.getTime() < Date.now() - 3600 * 1000 * 24 * 1
}

// 更换类型
let getradio = (e) => {
	if (e == 1) {
		for (let item of data.info.content) {
			item.active_value = ''
			if (data.info.fd_type == 2 || data.info.fd_type == 4) {
				item.g_id = ''
			}
		}
	} else {
		for (let item of data.info.content) {
			item.condition_value = ''
		}
	}
}

// 类型名称
let getname = (e, k) => {
	let arr = [
		$t('machine.types.undefined'),
		$t('marketing.reduction.gift'),
		$t('order.consume.discountAmount') + '($)',
		$t('marketing.preferential.giftRate') + '(%)',
		$t('marketing.preferential.discounts') + '(%)'
	]
	if (k == 2) {
		arr = [
			$t('machine.types.undefined'),
			$t('marketing.preferential.minAmount'),
			$t('marketing.reduction.minQuantity'),
			$t('marketing.reduction.sku')
		]
	}

	return arr[e]
}

// 添加活动说明
let addmance = () => {

	data.info.content.push({
		id: new Date().getTime() + 1,
		condition_value: '',
		g_id: '',
		active_value: '',
		fdc_sort: '1'
	})
}

// 删除说明
let dels = (e) => {
	let obj = data.info.content[e]

	if (obj.fdc_id != undefined) {
		data.info.delContent.push(obj.fdc_id)
	}

	data.info.content.splice(e, 1)
}
let onVisibleChange = () => {
	data.groupValue = []
}
// 选中分组/设备
let getmping = (e, k) => {
	let obj = ''
	let status = true
	if (k == 1) {
		// 分组
		data.nodesData.map((item) => {
			if (item.value === e[e.length - 1]) obj = item
		})
		for (let item of data.grouping) {
			if (item.value == obj.value) {
				status = false
			}
		}
	} else {
		// 设备
		data.maclist.map((item) => { if (item.machine_id === e) obj = item })
		for (let item of data.grouping) {
			if (item.m_id == obj.m_id) {
				status = false
			}
		}
		data.macping = ''
	}
	if (status) {
		data.grouping.push(obj)
	}
}

// 删除选中的设备分组/设备
let handleClose = (e) => {
	data.grouping.splice(e, 1)
}

// 保存
let submit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid, fields) => {
		if (valid) {
			let status = false
			let info = data.info
			let num = 0
			let machine = []
			let obj = {
				fd_id: info.fd_id,
				fd_name: info.fd_name,
				start_date: '',
				end_date: '',
				fd_type: info.fd_type,
				condition_type: info.condition_type,
				desc: info.desc,
				machineList: '',
				content: [],
				delContent: info.delContent.join(','),
				exclusion: info.exclusion ? 1 : 2
			}

			if (obj.condition_type == 0) {
				if (obj.fd_type != 3) {
					ElMessage({
						message: $t('message.unlimitedLimit'),
						type: 'error'
					})
					return
				}
			}

			obj.start_date = Math.floor(data.info.datel / 1000)
			obj.end_date = ''
			if (data.timetype == 1) {
				obj.start_date = Math.floor(data.info.date[0] / 1000)
				obj.end_date = Math.floor(data.info.date[1] / 1000)
			}

			for (let item of data.info.content) {
				let content = {}

				if (item.fdc_id != undefined) {
					content.fdc_id = item.fdc_id
				}

				// 条件类型判断
				if (data.info.condition_type != 0 && item.condition_value != '') {
					if (item.condition_value == '') {
						status = true
					} else {
						content.condition_value = item.condition_value
					}
				}

				// 商品判断
				if (data.info.fd_type == 1 || data.info.fd_type == 3) {
					if (item.g_id == '') {
						status = true
					} else {
						content.g_id = item.g_id
					}
				}

				// 活动类型判断
				if (data.info.fd_type != 1) {
					if (item.active_value == '') {
						status = true
					} else {
						content.active_value = item.active_value
					}

				}

				if (content.condition_value != undefined || content.g_id != undefined || content.active_value != undefined) {
					num++
					content.sort = num
					obj.content.push(content)
				}
				content.fdc_sort = item.fdc_sort
			}

			if (status == true) {
				ElMessage({
					message: $t('message.pleaseActivityRules'),
					type: 'error'
				})
				return
			}

			if (data.grouping.length == 0) {
				ElMessage({
					message: $t('message.pleaseSelectMachine'),
					type: 'error'
				})
				return
			}

			if (data.grouping.length != 0) {
				let grouping = []
				for (let item of data.grouping) {
					// 设备
					if (item.mg_id != undefined) {
						data.bindmacping.map((ime) => {
							if (item.mg_id === ime.mg_id) {
								grouping.push(ime.machine_id)
							}
						})
					}

					if (item.machine_id != undefined) {
						grouping.push(item.machine_id)
					}
					// 设备分组
					if (item.value != undefined) {
						data.bindmacping.map((ime) => {
							if (item.value === ime.mg_id) {
								grouping.push(ime.machine_id)
							}
						})
					}
				}
				// 设备分组放入指定设备中
				machine = [...machine, ...grouping]
			}

			// 去除重复的设备编号
			machine = [...new Set(machine)]
			obj.machineList = machine.join(',')

			data.mtloading = true
			updateactivityfd(obj).then(res => {
				data.mtloading = false
				if (res.state == 200) {
					ElMessage({
						message: $t('message.modifySuccess'),
						type: 'success'
					})
					router.back()
					return
				}
				ElMessage({

					message: $t('message.networkFailed'),
					type: 'error'
				})
			})
		}
	})
}

getfind()

</script>
<style type="text/css">
.dashed {
	border: 2px dashed var(--el-border-color);
}
</style>